package com.business.system.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.parser.deserializer.DateDeserializer;
import com.business.system.bean.WxUserBean;

import java.lang.reflect.Type;
import java.util.Date;

public class JCDateDeserializer extends DateDeserializer {
    public static final JCDateDeserializer instance = new JCDateDeserializer();

    public JCDateDeserializer() {
    }

    @Override
    protected <T> T cast(DefaultJSONParser parser, Type clazz, Object fieldName, Object val)
    {
        if (val == null) {
            return null;
        } else if (val instanceof String) {
            String strVal = (String) val;
            if (strVal.length() == 0) {
                return null;
            } else if (strVal.equals("0000-00-00")) {
                parser.setDateFormat("yyyy-MM-dd");
            }
        }
        return super.cast(parser, clazz, fieldName, val);
    }

    public static void main(String[] args) {
        String jsonStr = "{\"birthday\":\"2019-12-11\"}";
        ParserConfig jcParserConfig = new ParserConfig();
        jcParserConfig.putDeserializer(Date.class, JCDateDeserializer.instance);
        WxUserBean resultObject = JSON.parseObject(jsonStr, WxUserBean.class, jcParserConfig, JSON.DEFAULT_PARSER_FEATURE);
        System.out.println(resultObject.getBirthday());
    }
}